package com.weiqiao.mall.service.impl;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CardCommodityEntity;
import com.weiqiao.mall.domain.CommodityEntity;
import com.weiqiao.mall.repository.ICardCommodityRepository;
import com.weiqiao.mall.repository.ITeamCommodityRepository;
import com.weiqiao.mall.service.ICardCommodityService;
import com.weiqiao.utils.DateUtil;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.SecurityUtils;
import com.weiqiao.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("CardCommodityServiceImpl")
public class CardCommodityServiceImpl implements ICardCommodityService {

    @Autowired
    private ICardCommodityRepository cardCommodityRepository;

    /**
     * 信用卡商品佣金设置表
     */
    @Autowired
    private ITeamCommodityRepository commodityCommissionSetRepository;


    @Override
    public boolean addCardCommodity(CardCommodityEntity entity) {
        int companyId = SecurityUtils.getCompanyId();
        Bson filter = new Document("commodity_id", entity.getCommodity_id());
        cardCommodityRepository.addCardCommodity(companyId, filter, Document.parse(new Gson().toJson(entity)));
        return true;
    }


    @Override
    public int countCommodity(int companyId, Bson bson) {
        return cardCommodityRepository.countCommodity(companyId, bson);
    }

    @Override
    public List<CardCommodityEntity> findCommoditys(int companyId, Bson filter) {
        List<CardCommodityEntity> commodity = new ArrayList<>();
        List<String> list = cardCommodityRepository.findCommoditys(companyId, filter);
        for (String a : list) {
            CardCommodityEntity c = new Gson().fromJson(a, CardCommodityEntity.class);
            c.setCreate_date(DateUtil.timestampToString(c.getCreate_date()));
            commodity.add(c);
        }
        return commodity;
    }

    @Override
    public List<CardCommodityEntity> findCommoditys(int company_id, Document doc, Pageable pageable) {
        List<CardCommodityEntity> commodityList = new ArrayList<>();
        List<String> list = cardCommodityRepository.findCommodityByFilterAndPage(company_id, doc, pageable);
        if (!list.isEmpty()) {
            for (String a : list) {
                CardCommodityEntity c = new Gson().fromJson(a, CardCommodityEntity.class);
                c.setCreate_date(DateUtil.timestampToString(c.getCreate_date()));
                commodityList.add(c);
            }
        }
        return commodityList;
    }

    @Override
    public CardCommodityEntity findCommodityById(String commodity_id, int company_id) {
        Bson filter = Filters.eq("commodity_id", commodity_id);
        String s = cardCommodityRepository.findCommodityById(company_id, filter);
        return new Gson().fromJson(s, CardCommodityEntity.class);
    }

    @Override
    public boolean detCardCommodity(String commodity_id, int company_id) {
        Bson filter = Filters.eq("commodity_id", commodity_id);
        cardCommodityRepository.updateOneCommodity(company_id, filter, new Document("delete_flag", 1), false);
        return true;
    }

    @Override
    public boolean updateCardCommodityLabel(List<String> commodity_Ids, int company_id, List<String> labels) {
        // 查询条件，公司id，需要修改的商品。更改内容为商品标签集合
        Bson filter = Filters.in("commodity_id", commodity_Ids);
        cardCommodityRepository.updateMany(company_id, filter, new Document("label_brand_ids", labels), false);
        return false;
    }

    @Override
    public boolean updateCommodity(int companyId, Bson filter, Document doc) {
        return cardCommodityRepository.updateMany(companyId, filter, doc, false);
    }


    /**
     * 保存宝贝标签页面右侧勾选的宝贝
     *
     * @param request
     * @return
     */
    @Override
    public ResponseEntity saveCheckProduct(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        String commodityIds = request.getParameter("commodity_id");
        List<String> commodityIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(commodityIds)) {
            commodityIdList = Arrays.asList(commodityIds.split(","));
        }
        Bson filter = Filters.and(Filters.eq("delete_flag", 0), Filters.in("commodity_id", commodityIdList),
                Filters.eq("company_id", companyId));
        List<String> stringList = cardCommodityRepository.findCommoditys(companyId, filter);
        Map<String, Object> resultMap = new HashMap<>(2);
        try {
            String labelId = request.getParameter("label_id");
            // 保存之前先移除labelId关联的商品
            if (StringUtils.isNotBlank(labelId)) {
                List<String> paramList = new ArrayList<>();
                paramList.add(labelId);
                filter = Filters.and(Filters.eq("delete_flag", 0), Filters.in("label_brand_ids", paramList),
                        Filters.eq("company_id", companyId));
                List<String> repositoryCommoditys = cardCommodityRepository.findCommoditys(companyId, filter);
                if (CollectionUtils.isNotEmpty(repositoryCommoditys)) {
                    for (String str : repositoryCommoditys) {
                        CardCommodityEntity commodityEntity = new Gson().fromJson(str, CardCommodityEntity.class);
                        if (commodityEntity != null) {
                            List<String> label_brand_ids = commodityEntity.getLabel_brand_ids();
                            if (CollectionUtils.isNotEmpty(label_brand_ids)) {
                                Iterator<String> iterator = label_brand_ids.iterator();
                                while (iterator.hasNext()) {
                                    if (Objects.equals(labelId, iterator.next())) {
                                        iterator.remove();
                                    }
                                }
                                Bson query = Filters.eq("commodity_id", commodityEntity.getCommodity_id());
                                Document document = new Document();
                                document.append("label_brand_ids", label_brand_ids);
                                cardCommodityRepository.updateOneCommodity(companyId, query, document, false);
                            }
                        }
                    }
                }
            }
            // 开始保存新的 labelId 与商品的关系
            for (String str : stringList) {
                CardCommodityEntity commodityEntity = new Gson().fromJson(str, CardCommodityEntity.class);
                // 取出之前的标签id
                List<String> label_brand_ids = commodityEntity.getLabel_brand_ids();
                if (CollectionUtils.isNotEmpty(label_brand_ids)) {
                    label_brand_ids.add(labelId);
                } else {
                    label_brand_ids = new ArrayList<>();
                    label_brand_ids.add(labelId);
                }
                Document document = new Document();
                document.append("label_brand_ids", label_brand_ids);
                Bson query = Filters.eq("commodity_id", commodityEntity.getCommodity_id());
                cardCommodityRepository.updateOneCommodity(companyId, query, document, false);
            }
        } catch (JsonSyntaxException e) {
            resultMap.put("result", false);
            resultMap.put("msg", "保存失败");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        resultMap.put("result", true);
        resultMap.put("msg", "保存成功");
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    @Override
    public List<Map<String, Object>> exportCommodityInfo(int companyId, Bson filter) {
        List<Map<String, Object>> exportContent = new ArrayList<>();
        List<String> list = cardCommodityRepository.findCommoditys(companyId, filter);
        if (list != null && list.size() > 0) {
            for (String str : list) {
                CardCommodityEntity entity = new Gson().fromJson(str, CardCommodityEntity.class);
                exportContent.add(createExcelContent(entity));
            }
        }
        return exportContent;
    }


    /**
     * excel 内容组装
     *
     * @param entity 商品信息
     */
    public Map<String, Object> createExcelContent(CardCommodityEntity entity) {
        Map map = new LinkedHashMap();
        map.put("商品id", entity.getCommodity_id());
        map.put("商品名称", entity.getName());
        map.put("商品分类", entity.getVariety_name());
        map.put("状态", entity.getState() == 1? "仓库中": "已上架");
        map.put("创建时间", DateUtil.timestampToString(entity.getCreate_date()));
        return map;
    }
}
